package com.cloud.quickcore.admin.service;

import com.cloud.quickcommon.biz.BaseBizService;
import com.cloud.quickcommon.exception.BusinessException;
import com.cloud.quickcore.admin.dao.SysRoleRepository;
import com.cloud.quickcore.admin.dto.SysRoleDto;
import com.cloud.quickcore.admin.entity.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * 角色管理--service
 *
 * @author NiJo_H
 * @version 1.0
 * @date 2019/8/11 14:19
 */
@Service
public class SysRoleService implements BaseBizService<SysRoleDto, SysRole, Long> {
    @Autowired
    private SysRoleRepository roleRepository;

    @Override
    public SysRole save(SysRoleDto dto) {
        return roleRepository.save(dto.convertEntity());
    }

    @Override
    public SysRole update(SysRoleDto dto) {
        return roleRepository.save(dto.convertEntity());
    }

    @Override
    public void romve(Long id) {
        SysRole sysRole = roleRepository.findById(id).orElseThrow(() -> new BusinessException("未查询到角色信息!"));
        sysRole.setDeleted(true);
        roleRepository.save(sysRole);
    }

    @Override
    public Optional<SysRole> findById(Long id) {
        return Optional.empty();
    }

    @Override
    public List<SysRole> findAll() {
        return roleRepository.findAll();
    }

    /**
     * 通过角色字符串查询角色
     *
     * @param roleCode 角色字符串
     * @return SysRole 角色对象
     */
    public SysRole findRoleCode(String roleCode) {
        SysRole sysRole = new SysRole();
        sysRole.setRoleCode(roleCode);
        Optional<SysRole> opt = roleRepository.findOne(Example.of(sysRole));
        return opt.isPresent() ? opt.get() : null;
    }
}
